/**
 * 免密码安全JavaScript资源
 * 提供Token验证和资源管理功能
 */

class PasswordlessResourceManager {
    constructor() {
        this.baseUrl = window.location.origin;
        console.log('免密码资源管理器已初始化');
    }
    
    /**
     * 生成安全URL
     */
    async generateSecureUrl(resourcePath) {
        try {
            const response = await fetch('/api/generate-secure-url', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ resourcePath })
            });
            
            if (!response.ok) {
                throw new Error('生成URL失败');
            }
            
            return await response.json();
        } catch (error) {
            console.error('生成安全URL失败:', error);
            return null;
        }
    }
    
    /**
     * 验证当前页面资源权限
     */
    async validateCurrentResources() {
        const resources = [
            ...document.querySelectorAll('link[rel="stylesheet"]'),
            ...document.querySelectorAll('script[src]'),
            ...document.querySelectorAll('img[src]')
        ];
        
        let validCount = 0;
        let totalCount = 0;
        
        for (const resource of resources) {
            const url = new URL(resource.src || resource.href, this.baseUrl);
            
            // 只验证受保护资源
            if (url.pathname.startsWith('/protected/')) {
                totalCount++;
                const token = url.searchParams.get('token');
                const timestamp = url.searchParams.get('t');
                
                if (token && timestamp) {
                    const isValid = await this.validateResourceAccess(
                        url.pathname, 
                        token, 
                        parseInt(timestamp)
                    );
                    
                    if (isValid) {
                        validCount++;
                        this.markResourceValid(resource);
                    } else {
                        this.markResourceInvalid(resource);
                    }
                }
            }
        }
        
        this.showValidationResult(validCount, totalCount);
    }
    
    /**
     * 验证单个资源访问权限
     */
    async validateResourceAccess(resourcePath, token, timestamp) {
        try {
            const response = await fetch(
                `/api/validate-token?token=${token}&resourcePath=${encodeURIComponent(resourcePath)}&timestamp=${timestamp}`
            );
            
            if (!response.ok) {
                return false;
            }
            
            const data = await response.json();
            return data.valid && data.timestampValid;
        } catch (error) {
            console.error('验证请求失败:', error);
            return false;
        }
    }
    
    /**
     * 标记资源为有效
     */
    markResourceValid(resource) {
        resource.style.border = '3px solid #27ae60';
        resource.style.boxShadow = '0 0 10px rgba(39, 174, 96, 0.5)';
    }
    
    /**
     * 标记资源为无效
     */
    markResourceInvalid(resource) {
        resource.style.border = '3px solid #e74c3c';
        resource.style.boxShadow = '0 0 10px rgba(231, 76, 60, 0.5)';
    }
    
    /**
     * 显示验证结果
     */
    showValidationResult(validCount, totalCount) {
        const message = `资源验证完成: ${validCount}/${totalCount} 个资源验证通过`;
        
        // 创建提示框
        const alert = document.createElement('div');
        alert.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${validCount === totalCount ? '#27ae60' : '#e74c3c'};
            color: white;
            padding: 15px 20px;
            border-radius: 8px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            z-index: 1000;
            font-weight: bold;
        `;
        alert.textContent = message;
        
        document.body.appendChild(alert);
        
        // 3秒后自动移除
        setTimeout(() => {
            document.body.removeChild(alert);
        }, 3000);
    }
    
    /**
     * 刷新资源URL（重新加载页面）
     */
    refreshResources() {
        window.location.reload();
    }
    
    /**
     * 解析URL参数
     */
    parseUrlParams(url) {
        const urlObj = new URL(url, this.baseUrl);
        return {
            token: urlObj.searchParams.get('token'),
            timestamp: urlObj.searchParams.get('t'),
            clientId: urlObj.searchParams.get('clientId')
        };
    }
}

// 初始化资源管理器
const resourceManager = new PasswordlessResourceManager();

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    console.log('免密码安全资源页面已加载');
    
    // 更新当前时间显示
    updateCurrentTime();
    
    // 绑定全局函数
    window.validateCurrentResources = () => resourceManager.validateCurrentResources();
    window.refreshResources = () => resourceManager.refreshResources();
    
    // 显示页面加载信息
    const loadTime = performance.now();
    console.log(`页面加载耗时: ${loadTime.toFixed(2)}ms`);
});

/**
 * 更新当前时间显示
 */
function updateCurrentTime() {
    const timeElement = document.getElementById('current-time');
    if (timeElement) {
        setInterval(() => {
            timeElement.textContent = Date.now();
        }, 1000);
    }
}

/**
 * 复制安全URL到剪贴板
 */
function copySecureUrl(url) {
    navigator.clipboard.writeText(url).then(() => {
        alert('URL已复制到剪贴板');
    }).catch(err => {
        console.error('复制失败:', err);
    });
}
